package com.newegg.whois.search;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xbill.DNS.Address;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.MXRecord;
import org.xbill.DNS.Record;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;

import com.newegg.whois.model.DomainInfo;
import com.newegg.whois.util.DomainUtil;

public class DNSUtil {
	
	public static Map<String, String> nslookup(DomainInfo info) throws TextParseException{
		Map<String, String> result = new HashMap<>();
		result.put("Lookup.A", a(info));
		result.put("Lookup.CNAME", cname(info));
		result.put("Lookup.MX", mx(info));
		result.put("Lookup.NS", ns(info));
		result.put("Lookup.IP", ip(info));
		return result;
	}
	
	public static String a(DomainInfo info) throws TextParseException {
		List<String> aList = new ArrayList<>(); 
		Lookup lookup = new Lookup(info.getSubDomainName(), Type.A);
		Record[] records = lookup.run();
		if(records == null){ return null; }
		for (Record record : records) {
			aList.add(record.rdataToString());
		}
		return String.join(",", aList);
	}
	
	public static String ns(DomainInfo info) throws TextParseException {
		List<String> aList = new ArrayList<>(); 
		Lookup lookup = new Lookup(info.getDomain() + "." + info.getTld(), Type.NS);
		Record[] records = lookup.run();
		if(records == null){ return null; }
		for (Record record : records) {
			aList.add(record.rdataToString());
		}
		return String.join(",", aList);
	}
	
	public static String cname(DomainInfo info) throws TextParseException {
		List<String> aList = new ArrayList<>(); 
		Lookup lookup = new Lookup(info.getDomain() + "." + info.getTld(), Type.CNAME);
		Record[] records = lookup.run();
		if(records == null){ return null; }
		for (Record record : records) {
			aList.add(record.rdataToString());
		}
		return String.join(",", aList);
	}
	
	public static String mx(DomainInfo info) throws TextParseException {
		List<String> aList = new ArrayList<>(); 
		Lookup lookup = new Lookup(info.getDomain() + "." + info.getTld(), Type.MX);
		Record[] records = lookup.run();
		if(records == null){ return null; }
		for (Record record : records) {
			MXRecord mx = (MXRecord) record;
			aList.add(mx.getTarget().toString());
		}
		return String.join(",", aList);
	}
	
	public static String ip(DomainInfo info) {
		List<String> aList = new ArrayList<>(); 
		try {
			InetAddress addr = Address.getByName(info.getSubdomain() + "." + info.getDomain() + "." + info.getTld());
			aList.add(addr.getHostAddress().toLowerCase());
		} catch (Exception e) { }
		return String.join(",", aList);
	}
	
	public static void main(String[] args) {
		DomainInfo info = DomainUtil.getDomainInfo("www.geekcode.com.cn");
		System.out.println(ip(info));
	}
}
